package com.bretagne5.radio;

import java.io.IOException;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class ServiceRadio extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {

	public static final String NOTIFICATION = "com.bretagne5.radio",
			SERVICE_RECEIVER = "com.bretagne5.radio.service";
    public static final String ACTION_PLAY = "PLAY";
    private static String mUrl = "http://bretagne5ing.streamakaci.com/bretagne5.mp3";
    private static ServiceRadio mInstance = null;

    private static MediaPlayer mMediaPlayer = null;    // The Media Player
    private static String mSongTitle;

    NotificationManager mNotificationManager;
    Notification mNotification = null;
    final int NOTIFICATION_ID = 1;
    
    // indicates the state our service:
    enum State {
        Retrieving, // the MediaRetriever is retrieving music
        Stopped, // media player is stopped and not prepared to play
        Preparing, // media player is preparing...
        Playing, // playback active (media player ready!). (but the media player may actually be
                    // paused in this state if we don't have audio focus. But we stay in this state
                    // so that we know we have to resume playback once we get focus back)
        Paused
        // playback paused (media player ready!)
    };

    static State mState = State.Retrieving;
    
    public static boolean getServiceRadioStarted(){
    	
    	return  (mInstance == null)? true : false ;
    }

	@Override
    public void onCreate() {
		
        mInstance = this;
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                
        registerReceiver(receiver, new IntentFilter(ServiceRadio.SERVICE_RECEIVER));
    }
	
	
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    	
    	if (intent != null){
	        if (intent.getAction().equals(ACTION_PLAY)) {
	            mMediaPlayer = new MediaPlayer(); // initialize it here
	            mMediaPlayer.setOnPreparedListener(this);
	            mMediaPlayer.setOnErrorListener(this);
	            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
	            initMediaPlayer();
	        }
    	}
        return START_STICKY;
    }

    private void initMediaPlayer() {
        try {
            mMediaPlayer.setDataSource(mUrl);
        } catch (IllegalArgumentException e) {
            // ...
        } catch (IllegalStateException e) {
            // ...
        } catch (IOException e) {
            // ...
        }

        try {
            mMediaPlayer.prepareAsync(); // prepare async to not block main thread
        } catch (IllegalStateException e) {
            // ...
        }
        mState = State.Preparing;
    }

    /** Called when MediaPlayer is ready */
    @Override
    public void onPrepared(MediaPlayer player) {

    	
    	Intent intent = new Intent("com.bretagne5.radio");
	    intent.putExtra("state", "ready");
	    sendBroadcast(intent);
	    mState = State.Paused;
	
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onDestroy() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
        }
        mState = State.Retrieving;
    }

    public static  MediaPlayer getMediaPlayer() {
        return mMediaPlayer;
    }

    public  void startMusic() {
        if (!mState.equals(State.Preparing) &&!mState.equals(State.Retrieving)) {
            mMediaPlayer.start();
            mState = State.Playing;
            updateNotification(mSongTitle + "(playing)");
            setUpAsForeground(getSongTitle());
        }
    }
    
    public  void pauseMusic() {
        if (mState.equals(State.Playing)) {
            mMediaPlayer.pause();
            mState = State.Paused;
            updateNotification(mSongTitle + "(paused)");
            setUpAsForeground(getSongTitle());
        }
    }
    
    public  void stopMusic() {
    	
		if (mState.equals(State.Playing) || mState.equals(State.Paused)){
			mMediaPlayer.stop();
			mMediaPlayer.release();
			mMediaPlayer = new MediaPlayer(); // initialize it here
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.setOnErrorListener(this);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            initMediaPlayer();
			
			mState = State.Stopped;
     
	        stopForeground(true);
		}
	}

    public boolean isPlaying() {
        if (mState.equals(State.Playing)) {
            return true;
        }
        return false;
    }   

    public static ServiceRadio getInstance() {
        return mInstance;
    }

    public static void setSong( String title) {
        mSongTitle = title;
    }

    public String getSongTitle() {
        return mSongTitle;
    }

    /** Updates the notification. */
    static void updateNotification(String text) {
        // Notify NotificationManager of new intent
    }

    /**
     * Configures service as a foreground service. A foreground service is a service that's doing something the user is
     * actively aware of (such as playing music), and must appear to the user as a notification. That's why we create
     * the notification here.
     */
    private void setUpAsForeground(String text) {
        PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), MainActivity.class),
                        PendingIntent.FLAG_UPDATE_CURRENT);
        mNotification = new Notification();
        mNotification.tickerText = "Radio en cours";
        mNotification.icon = R.drawable.ic_launcher;
        mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
        mNotification.setLatestEventInfo(getApplicationContext(), getResources().getString(R.string.app_name), text, pi);
        startForeground(NOTIFICATION_ID, mNotification);
        
    }
    
    BroadcastReceiver receiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bundle = intent.getExtras();
		      if (bundle != null) {
		    	  
		    	switch ((String)bundle.get("state")) {
				case "start":
					
					Log.d("radio", "start");
					startMusic();
					
					break;
					
				case "pause":
					
					Log.d("radio", "pause");
					pauseMusic();
					
					break;
					
				case "stop":
					
					Log.d("radio", "stop");
					stopMusic();
					
					break;

				default:
					break;
				}
  
		      }
			
		}
	};

}